import axios from 'axios';
import type { AxiosInstance } from 'axios';
import { showMessage } from '../utils/message';

const BASE_URL = 'http://localhost:8005/submission';

export interface SubmissionData {
  problem_id: number;
  code: string;
  language: string;
}

export interface SubmissionResult {
  id: number;
  user_id: number;
  problem_id: number;
  status: string;
  language: string;
  code: string;
  execution_time?: number;
  memory_usage?: number;
  created_at: string;
  error_message?: string;
}

const api: AxiosInstance = axios.create({
  baseURL: BASE_URL,
  timeout: 10000, // Longer timeout for submissions
});

// Response interceptor
api.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code !== 200) {
      showMessage(res);
      return Promise.reject(res);
    }
    return res;
  },
  (error) => {
    showMessage({
      code: error.response?.status || 500,
      msg: error.response?.data?.msg || '提交失败',
    });
    return Promise.reject(error);
  }
);

const submissionApi = {
  // 提交代码
  async submit(data: SubmissionData): Promise<SubmissionResult> {
    const response = await api.post('/submit', data);
    return response.data;
  },

  // 获取提交结果
  async getResult(submissionId: number): Promise<SubmissionResult> {
    const response = await api.get(`/result/${submissionId}`);
    return response.data;
  },

  // 获取提交列表
  async getList(page = 1, pageSize = 10, filters?: {
    problem_id?: number;
    status?: string;
    language?: string;
  }) {
    const response = await api.get('/', {
      params: {
        page,
        pageSize,
        ...filters
      }
    });
    return response.data;
  }
};

export default submissionApi;
